package br.com.eduquiz.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

public class Tools {
	
	public static final String DEFAULT_ALGORITHM_ENCRIPT = "SHA-256";

	public static String getClientIP() {
		HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
		
		return request.getRemoteAddr();
	}
	
	public static String encriptar(String senha, String algorithm) {
		try {
			MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
			byte digest[] = messageDigest.digest(senha.getBytes("UTF-8"));
			
			StringBuilder hexString = new StringBuilder();
			
			for (byte b : digest) {
				hexString.append(Integer.toHexString(0xFF & b));
			}
			
			return hexString.toString();
			
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return null;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public static String encriptar(String senha) {
		return encriptar(senha, DEFAULT_ALGORITHM_ENCRIPT);
	}
	
}
